//
//  EMDetailInfoViewController.m
//  ElectronicMall
//
//  Created by 史伟文 on 15/1/10.
//  Copyright (c) 2015年 cczu. All rights reserved.
//

#import "EMDetailInfoViewController.h"
#import "UINavigationController+EMNavi.h"
#import "MBProgressHUD.h"
#import "AppDelegate.h"
#import "EMDetailInfoReqBody.h"
#import "EMDetailInfoRespBody.h"
#import "EMDetailInfo.h"
#import "UIImageView+WebCache.h"
#import "EMSegmentedControl.h"
#import "EMGetCommentReqBody.h"
#import "EMGetCommentRespBody.h"
#import "UserInfo.h"
#import "EMLoginViewController.h"
#import <ShareSDK/ShareSDK.h>
#import "EMShoppingCartViewController.h"

@interface EMDetailInfoViewController ()
{
    UITableView *myTableView;
    UIImageView *imgView;
    EMImageScrollView *csView;
    CGFloat imageHeight;
    CGFloat imageWidth;
    CGFloat detailImageHeight;
    CGFloat detailImageWidth;
    AppDelegate *app;
    EMDetailInfo *info;
    BOOL isDetail;
    UIImageView *imgV;
    EMSegmentedControl *seg;
    NSArray *commentsArray;
}

@end

@implementation EMDetailInfoViewController
- (void)hideBottomBar
{
    for(UIView *view in self.view.subviews)
    {
        if([view isKindOfClass:[UITabBar class]])
            view.hidden = YES;
    }
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self hideBottomBar];
    app = (AppDelegate *)[UIApplication sharedApplication].delegate;
    [self.navigationController setNavigationMode:EMNavigationModeDefault andSubMode:0];
    self.navigationItem.title = @"商品详情";
    commentsArray = [[NSArray alloc] init];
    
    imageHeight = 1;
    imageWidth = 1;
    detailImageHeight = 1;
    detailImageWidth = 1;
    isDetail = YES;
    UIButton *button =[UIButton buttonWithType:UIButtonTypeCustom];
    button.frame=CGRectMake(0, 0, 30, 32);
    [button setImage:[UIImage imageNamed:@"button_导航_返回_白"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(backAction:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem =[[UIBarButtonItem alloc]initWithCustomView:button];
    
    UIButton *shareButton = [UIButton buttonWithType:UIButtonTypeCustom];
    shareButton.frame = CGRectMake(0, 0, 44, 44);
    [shareButton setImage:[UIImage imageNamed:@"icon_详情_分享"] forState:UIControlStateNormal];
    [shareButton addTarget:self action:@selector(shareAction:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:shareButton];
    
    
    [self getGoodDetailInfo];
}
- (void)backAction: (UIButton *)sender
{
    self.navigationController.navigationBar.barTintColor = RGB(242, 242, 242);
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)shareAction:(UIButton *)sender
{
    NSArray *shareList = [ShareSDK getShareListWithType: ShareTypeSinaWeibo, ShareTypeTencentWeibo, ShareTypeQQ, ShareTypeQQSpace, ShareTypeWeixiSession, ShareTypeWeixiTimeline, nil];
    NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"ShareSDK" ofType:@"png"];
    id<ISSContent> publishContent = [ShareSDK content:@"我正使用沃佳鲜生购买商品，真的很好用哦。亲，一起来试试吧！"
                                       defaultContent:@""
                                                image:[ShareSDK imageWithPath:imagePath]
                                                title:@"沃佳鲜生"
                                                  url:@"http://www.wojiaxiansheng.com"
                                          description:@"我正使用沃佳鲜生购买商品，真的很好用哦。亲，一起来试试吧！"
                                            mediaType:SSPublishContentMediaTypeNews];
    //创建弹出菜单容器
    id<ISSContainer> container = [ShareSDK container];
    [container setIPadContainerWithView:sender arrowDirect:UIPopoverArrowDirectionUp];
    
    //弹出分享菜单
    [ShareSDK showShareActionSheet:container
                         shareList:shareList
                           content:publishContent
                     statusBarTips:YES
                       authOptions:nil
                      shareOptions:nil
                            result:^(ShareType type, SSResponseState state, id<ISSPlatformShareInfo> statusInfo, id<ICMErrorInfo> error, BOOL end) {
                                
                                if (state == SSResponseStateSuccess)
                                {
                                    NSLog(NSLocalizedString(@"TEXT_ShARE_SUC", @"分享成功"));
                                }
                                else if (state == SSResponseStateFail)
                                {
                                    NSLog(NSLocalizedString(@"TEXT_ShARE_FAI", @"分享失败,错误码:%d,错误描述:%@"), [error errorCode], [error errorDescription]);
                                }
                            }];
}

- (void)getGoodCommentInfo
{
    [MBProgressHUD  showHUDAddedTo:self.navigationController.view animated:YES];
    EMGetCommentReqBody *reqBody = [[EMGetCommentReqBody alloc] init];
    reqBody.JUDGEMETHOD = @"GOOD-COMMENTS";
    reqBody.ID = info.m_id;
    reqBody.PAGE = @"1";
    reqBody.ALLPAGE = @"5";
    HessianFormDataRequest *request = [[HessianFormDataRequest alloc] init];
    // 模型转字典
    request.postData = reqBody.keyValues;
    [request startRequestWithURL:baseURL andCompletionBlcok:^(NSDictionary *respInfo) {
        // 将返回的字典转成模型，键的名称必须相同
        EMGetCommentRespBody *respBody = [EMGetCommentRespBody objectWithKeyValues:respInfo];
        [MBProgressHUD hideHUDForView:self.navigationController.view animated:YES];
        NSLog(@"%@", respInfo);
        if ([respBody.ERRORCODE isEqualToString: @"0000"]) {
            commentsArray = respBody.COMMENTS;
        } else {
            [app showTip:respInfo[@"ERRORDESTRIPTION"]];
        }
        
    } andFailedBlock:^{
        
        [app showTip:@"无法连接服务器、请稍后再试"];
    }];
    

}

- (void)getGoodDetailInfo
{
    [MBProgressHUD  showHUDAddedTo:self.navigationController.view animated:YES];
    EMDetailInfoReqBody *reqBody = [[EMDetailInfoReqBody alloc] init];
    reqBody.JUDGEMETHOD = @"GOOD-DETAILS-PAGE";
    reqBody.ID = self.goodID;
    HessianFormDataRequest *request = [[HessianFormDataRequest alloc] init];
    // 模型转字典
    request.postData = reqBody.keyValues;
    [request startRequestWithURL:baseURL andCompletionBlcok:^(NSDictionary *respInfo) {
        // 将返回的字典转成模型，键的名称必须相同
        EMDetailInfoRespBody *respBody = [EMDetailInfoRespBody objectWithKeyValues:respInfo];
        [MBProgressHUD hideHUDForView:self.navigationController.view animated:YES];
        NSLog(@"%@", respInfo);
        if ([respBody.ERRORCODE isEqualToString: @"0000"]) {
            info = [[EMDetailInfo alloc] initWithGoodInfo:respBody.GOODINFO[0]];
            NSString *detailImgUrlString = info.m_detailImgUrl;
            NSArray *imgUrlArray = [detailImgUrlString componentsSeparatedByString:@","];
            
            imgV = [[UIImageView alloc] init];
            NSURL *aUrl = [NSURL URLWithString:imgUrlArray[0]];
//            NSError *error;
//            BOOL iii = [aUrl checkResourceIsReachableAndReturnError:&error];
            
            [imgV sd_setImageWithURL:aUrl completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                if (image) {
                    detailImageHeight = image.size.height;
                    detailImageWidth = image.size.width;
                    imgV.frame = CGRectMake(0, 0, W(320), H(detailImageHeight * 320 / detailImageWidth));
                }
                [myTableView reloadData];
                
                
            }];
        } else {
            [app showTip:respInfo[@"ERRORDESTRIPTION"]];
        }
        
    } andFailedBlock:^{
        
        [app showTip:@"无法连接服务器、请稍后再试"];
    }];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, W(320), H(568) - 64) style:UITableViewStylePlain];
    myTableView.delegate = self;
    myTableView.dataSource = self;
    myTableView.bounces = NO;
    myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:myTableView];
    
    UIView *controlView = [[UIView alloc] initWithFrame:CGRectMake([UIScreen mainScreen].bounds.size.width - 60, [UIScreen mainScreen].bounds.size.height - 60 - 64, 120, 120)];
    controlView.layer.cornerRadius = 60;
    controlView.backgroundColor = RGBA(112, 179, 81, 0.6);
    
    UIButton *addToCartBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [addToCartBtn setImage:[UIImage imageNamed:@"button_购物车_红"] forState:UIControlStateNormal];
    addToCartBtn.frame = CGRectMake(18, 15, 40, 40);
    [addToCartBtn addTarget:self action:@selector(addToCart:) forControlEvents:UIControlEventTouchUpInside];
    [controlView addSubview:addToCartBtn];
    [self.view addSubview:controlView];
    
    
    UIButton *cartBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [cartBtn setImage:[UIImage imageNamed:@"button_进入购物车"] forState:UIControlStateNormal];
    [cartBtn setFrame:CGRectMake(20, [UIScreen mainScreen].bounds.size.height - 64 - 49 - 30, 55, 55)];
    [cartBtn addTarget:self action:@selector(enterToCart:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:cartBtn];
}

#pragma mark - Image Scroll View Delegate and Datesource
- (NSInteger)numberOfPages
{
    NSArray *imgArray = [info.m_imgUrl componentsSeparatedByString:@","];
    return imgArray.count;
}

- (UIView *)pageAtIndex:(NSInteger)index
{
    NSArray *imgArray = [info.m_imgUrl componentsSeparatedByString:@","];
    
    
    UIImageView *view = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, W(320), H(250))];
    [view sd_setImageWithURL:[NSURL URLWithString:imgArray[index]]];
    
    return view;
}

- (void)didClickPage:(EMImageScrollView *)csView atIndex:(NSInteger)index
{

}

- (void)addToCart:(UIButton *)btn
{
    if ([UserInfo sharedUserInfo].m_isLogin) {
        [app addToCartWithID:info.m_id];
    } else {
        [app showTip:@"请先登录"];
        EMLoginViewController *controller = [[EMLoginViewController alloc] init];
        controller.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:controller animated:YES];
    }
    
    
}
- (void)enterToCart:(UIButton *)sender
{
    if ([UserInfo sharedUserInfo].m_isLogin) {
        EMShoppingCartViewController *controller = [[EMShoppingCartViewController alloc] init];
        [self.navigationController pushViewController:controller animated:YES];
    } else {
        [app showTip:@"请先登录"];
        EMLoginViewController *controller = [[EMLoginViewController alloc] init];
        controller.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:controller animated:YES];
    }
    
}
#pragma mark - UITableView delegate and dataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 5;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    } else if (section == 1) {
        return 4;
    } else if (section == 2) {
        return 4;
    } else if (section == 3) {
        return 1;
    } else {
        if (isDetail) {
            return 1;
        } else {
            return commentsArray.count;
        }
    }
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"celld12";
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    if (indexPath.section == 0) {

        csView = [[EMImageScrollView alloc] initWithFrame:CGRectMake(0, 0, W(320), H(250))];
        csView.delegate = self;
        csView.datasource = self;
        [cell addSubview:csView];
        return cell;
    } else if (indexPath.section == 1) {

        if (indexPath.row == 0) {
            cell.textLabel.text = info.m_name;
            cell.textLabel.textColor = [UIColor darkGrayColor];
            cell.textLabel.font = [UIFont fontWithName:HEITIMEDIUM size:16];
        } else if (indexPath.row == 1) {
            cell.textLabel.text = (NSNull *)info.m_goodDesc == [NSNull null] ? @"" : info.m_goodDesc;
            cell.textLabel.textColor = [UIColor orangeColor];
            cell.textLabel.font = [UIFont fontWithName:HEITIMEDIUM size:14];
        } else if (indexPath.row == 2) {
            if ([info.m_mode isEqualToString:@"0"]) {
                UILabel *nowPriceTitleLabel = [[UILabel alloc] initWithFrame:CGRectMake(W(40), 0, W(60), H(30))];
                nowPriceTitleLabel.text = @"价格:";
                [cell addSubview:nowPriceTitleLabel];
                UILabel *nowPriceLabel = [[UILabel alloc] initWithFrame:CGRectMake(W(100), 0, W(60), H(30))];
                nowPriceLabel.text = [NSString stringWithFormat:@"¥%@",info.m_nowPrice];
                nowPriceLabel.textColor = [UIColor redColor];
                nowPriceLabel.font = [UIFont fontWithName:HEITIMEDIUM size:18];
                [cell addSubview:nowPriceLabel];
            } else {
                UILabel *nowPriceTitleLabel = [[UILabel alloc] initWithFrame:CGRectMake(W(40), 0, W(60), H(30))];
                nowPriceTitleLabel.text = @"促销价:";
                [cell addSubview:nowPriceTitleLabel];
                UILabel *nowPriceLabel = [[UILabel alloc] initWithFrame:CGRectMake(W(100), 0, W(60), H(30))];
                nowPriceLabel.text = [NSString stringWithFormat:@"¥%@",info.m_nowPrice];
                nowPriceLabel.textColor = [UIColor redColor];
                nowPriceLabel.font = [UIFont fontWithName:HEITIMEDIUM size:18];
                [cell addSubview:nowPriceLabel];
                UILabel *originPriceTitleLabel = [[UILabel alloc] initWithFrame:CGRectMake(W(180), 0, W(60), H(30))];
                originPriceTitleLabel.text = @"原价:";
                [cell addSubview:originPriceTitleLabel];
                UILabel *originPriceLabel = [[UILabel alloc] initWithFrame:CGRectMake(W(220), 0, W(60), H(30))];
                NSMutableAttributedString *oPrice = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"¥%@", info.m_originPrice]];
                [oPrice addAttribute:NSStrikethroughStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:NSMakeRange(0, info.m_originPrice.length+1)];
                [oPrice addAttribute:NSForegroundColorAttributeName value:[UIColor grayColor] range:NSMakeRange(0, info.m_originPrice.length + 1)];
                originPriceLabel.attributedText = oPrice;
                [cell addSubview:originPriceLabel];
            }
            
        } else {
            
        }
        return cell;
    } else if (indexPath.section == 2){

        if (indexPath.row == 0) {
            UIView *tView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, W(320), 0.5)];
            tView.backgroundColor = RGB(112, 179, 81);
            [cell addSubview:tView];
            cell.textLabel.text = @"商品规格：";
            cell.textLabel.font = [UIFont fontWithName:HEITIMEDIUM size:16];
        } else if (indexPath.row == 1) {
            cell.textLabel.text = [NSString stringWithFormat:@"\t商品数量：%@", info.m_totalCount];
            cell.textLabel.font = [UIFont fontWithName:HEITIMEDIUM size:14];
        } else if (indexPath.row == 2) {
            cell.textLabel.text = [NSString stringWithFormat:@"\t商品重量：%@", info.m_weight];
            cell.textLabel.font = [UIFont fontWithName:HEITIMEDIUM size:14];
        } else {
            cell.textLabel.text = [NSString stringWithFormat:@"\t商品规格：%@", info.m_form];
            cell.textLabel.font = [UIFont fontWithName:HEITIMEDIUM size:14];
            UIView *bView = [[UIView alloc] initWithFrame:CGRectMake(0, 29, W(320), 0.5)];
            bView.backgroundColor = RGB(112, 179, 81);
            [cell addSubview:bView];
        }
        return cell;
    } else if (indexPath.section == 3) {

        seg = [[EMSegmentedControl alloc] initWithFrame:CGRectMake(W(10), 0, W(300), H(30))];
        [seg setTitleArray:@[@"商品详情", @"商品评价"]];
        [seg setActionBlock:^(NSUInteger index) {
            NSLog(@"%zd", index);
            
            if (index == 0) {
                isDetail = YES;
                [myTableView reloadData];
            } else {
                [self getGoodCommentInfo];
                isDetail = NO;
                NSIndexSet *indexSet = [[NSIndexSet alloc] initWithIndex:4];
                [myTableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationNone];
            }
            
            
        }];
        
            [cell addSubview:seg];
 
        return cell;

    } else {
        
        if (isDetail) {
            imgV.frame = CGRectMake(0, 0, W(320), H(detailImageHeight * 320 / detailImageWidth));
            [cell addSubview:imgV];
        } else {
            [imgV removeFromSuperview];
            UIView *commonView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, W(320), H(95))];
            
            NSArray *aComment = commentsArray[indexPath.row];
            UIImageView *commentImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"product01"]];
            commentImage.frame = CGRectMake(W(20), H(5), W(60), H(60));
            [commonView addSubview:commentImage];
            
            UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(W(20), H(70), W(60), H(20))];
            titleLabel.text = @"水果上市";
            titleLabel.textColor = [UIColor grayColor];
            titleLabel.textAlignment = NSTextAlignmentCenter;
            titleLabel.font = [UIFont fontWithName:HEITILIGHT size:14];
            [commonView addSubview:titleLabel];
            
            UILabel *contentLabel = [[UILabel alloc] initWithFrame:CGRectMake(W(100), H(5), W(210), H(60))];
            contentLabel.text = aComment[1];
            contentLabel.textColor = [UIColor grayColor];
            contentLabel.textAlignment = NSTextAlignmentLeft;
            contentLabel.font = [UIFont fontWithName:HEITILIGHT size:12];
            [commonView addSubview:contentLabel];
            
            UILabel *timeLabel = [[UILabel alloc] initWithFrame:CGRectMake(W(90), H(70), W(220), H(20))];
            timeLabel.text = aComment[2];
            timeLabel.textColor = [UIColor grayColor];
            timeLabel.textAlignment = NSTextAlignmentRight;
            timeLabel.font = [UIFont fontWithName:HEITILIGHT size:12];
            [commonView addSubview:timeLabel];
            
            [cell addSubview:commonView];
        }
        return cell;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return H(250);
    } else if (indexPath.section == 1) {
        if (indexPath.row == 3) {
            return H(15);
        } else {
            return H(30);
        }
    } else if (indexPath.section == 2) {
        return H(30);
    } else if (indexPath.section == 3) {
        return H(30);
    } else {
        if (isDetail) {
            return H(detailImageHeight * 320 / detailImageWidth);
        } else {
            return H(95);
        }
    }
}

//- (void)scrollViewDidScroll:(UIScrollView *)scrollView
//{
//    CGFloat yOffset = scrollView.contentOffset.y;
//    NSLog(@"%lf", yOffset);
//    if (yOffset < 0) {
//        if (yOffset > -100) {
//            CGFloat factor = ((ABS(yOffset)+120)*320)/120;
//            CGRect f = CGRectMake(-(factor-320)/2, yOffset, factor/5, 120+ABS(yOffset));
//            csView.frame = f;
//        } else {
//            CGRect f = csView.frame;
//            f.origin.y = yOffset;
//            csView.frame = f;
//        }
//    }
//}



@end
